import Taro from "@tarojs/taro"
import md5 from 'md5';
import dayjs from 'dayjs';
import { PayData } from "@/model/declare"
import { sceneDesktopManager } from '@/model/SceneDesktopManger'
import { DesktopOrderType } from '@/utils/constants';

export const getUserId = () => {
  const user_id = Taro.getStorageSync('user_id');
  if (!user_id) {
    Taro.navigateTo({
      url: '/pages/login/index'
    })
    return;
  }
  return user_id;
}
/**
     * @desc 一阶贝塞尔
     * @param {number} t 当前百分比
     * @param {Array} p1 起点坐标
     * @param {Array} p2 终点坐标
     */
export const oneBezier = (t, p1, p2) => {
  const [x1, y1] = p1;
  const [x2, y2] = p2;
  let x = x1 + (x2 - x1) * t;
  let y = y1 + (y2 - y1) * t;
  return [x, y];
}

/**
 * @desc 二阶贝塞尔
 * @param {number} t 当前百分比
 * @param {Array} p1 起点坐标
 * @param {Array} p2 终点坐标
 * @param {Array} cp 控制点
 */
export const twoBezier = (t, p1, cp, p2) => {
  const [x1, y1] = p1;
  const [cx, cy] = cp;
  const [x2, y2] = p2;
  let x = (1 - t) * (1 - t) * x1 + 2 * t * (1 - t) * cx + t * t * x2;
  let y = (1 - t) * (1 - t) * y1 + 2 * t * (1 - t) * cy + t * t * y2;
  return [x, y];
}
/**
* @desc 获取二阶贝塞尔曲线上的坐标点
* @param {Array} p1 起点坐标
* @param {Array} p2 终点坐标
* @param {Array} cp 控制点
*/
export const getTwoBezierPoints = (p1, p2, num) => {
  const cpx = p1[0] < p2[0] ? p1[0] + (p2[0] - p1[0]) / 2 : p2[0] + (p1[0] - p2[0]) / 2
  const cp = [cpx, p1[1] - 100]
  const points: Array<any> = []
  let t = 0;
  while (t < 1) {
    t += 1 / num
    points.push(twoBezier(t, p1, cp, p2))
  }
  return points
}
/**
 * @desc 三阶贝塞尔
 * @param {number} t 当前百分比
 * @param {Array} p1 起点坐标
 * @param {Array} p2 终点坐标
 * @param {Array} cp1 控制点1
 * @param {Array} cp2 控制点2
 */
export const threeBezier = (t, p1, cp1, cp2, p2) => {
  const [x1, y1] = p1;
  const [x2, y2] = p2;
  const [cx1, cy1] = cp1;
  const [cx2, cy2] = cp2;
  let x =
    x1 * (1 - t) * (1 - t) * (1 - t) +
    3 * cx1 * t * (1 - t) * (1 - t) +
    3 * cx2 * t * t * (1 - t) +
    x2 * t * t * t;
  let y =
    y1 * (1 - t) * (1 - t) * (1 - t) +
    3 * cy1 * t * (1 - t) * (1 - t) +
    3 * cy2 * t * t * (1 - t) +
    y2 * t * t * t;
  return [x, y];
}

export function isDef(value: any): boolean {
  return value !== undefined && value !== null;
}

export function isObj(x: any): boolean {
  const type = typeof x;
  return x !== null && (type === 'object' || type === 'function');
}

export function isNumber(value) {
  return /^\d+(\.\d+)?$/.test(value);
}

export function range(num: number, min: number, max: number) {
  return Math.min(Math.max(num, min), max);
}

export function nextTick(fn: Function) {
  setTimeout(() => {
    fn();
  }, 1000 / 30);
}

export const getCurrentStimp = () => Math.floor(Date.now() / 1000);

// 加密支付
export const getSign = (params, partnerKey) => {
  const keys = Object.keys(params);
  keys.sort((a, b) => a.charAt(0).charCodeAt() - b.charAt(0).charCodeAt());
  const stringA = keys.map(it => it + '=' + params[it]).join('&');
  const stringSignTemp = `${stringA}&key=${partnerKey}`; //注：key为商户平台设置的密钥key
  return md5(stringSignTemp).toUpperCase();
}


export const toDate = (time: number, num = 1000) => dayjs(time * num).format('YYYY-MM-DD HH:mm:ss')

// 防抖函数
export const debounce = (fn, interval = 300) => {
  let timeout: any = null;
  return function () {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      fn.apply(this, arguments);
    }, interval);
  };
}

export const scanCode = () => {
  Taro.scanCode({
    onlyFromCamera: true,
    success: (res) => {
      const { errMsg, path } = res;
      if (errMsg === 'scanCode:ok') {
        sceneDesktopManager.setOrderType(DesktopOrderType[0]);
        Taro.navigateTo({ url: `/${path}` });
      }
    }
  })
}


export const launchPay = (data: PayData) => {
  const { appid, prepay_id } = data;
  const timeStamp = getCurrentStimp();
  const params = {
    appId: appid,
    timeStamp: timeStamp.toString(),
    nonceStr: Math.random().toString(36).substr(2),
    package: `prepay_id=${prepay_id}`,
    signType: 'MD5',
  };


  const partner_key = Taro.getStorageSync('partner_key');
  const paySign = getSign(params, partner_key);
  Object.assign(params, { paySign });

  Taro.requestPayment({
    ...params,
    success: res => {
      Taro.showToast({
        title: "支付成功",
        icon: "success",
        duration: 1500,
        mask: false,
        success: res => {
          console.log('支付成功');
          console.log(res, '支付成功');
          Taro.showToast({ icon: 'success', title: '支付成功' })
          setTimeout(() => {
            Taro.navigateTo({ url: `/pages/activity/applySuccess/index` });
          }, 700);
        }
      });
    },
    fail: res => {
      console.log(res, '支付失败');
      Taro.showToast({ icon: 'none', title: '支付失败' })
      // setTimeout(() => {
      //   Taro.navigateTo({ url: `/pages/ucenter/orders/index?status=WAIT_PAY` });
      // }, 700);
    },
    complete: res => {
      console.log(res);
    }
  });

}


export const arrayToObject = (arr: any[], id = 'id', label = 'label') => arr.reduce((pre, next) => { pre[next[id]] = next[label]; return pre; }, {});
